$(function () {
	var url = location.search;
	var brandName=decodeURI(url);
	var brandId="";
	if(url!=null && url!="") {
		brandName = brandName.split("=")[1];
		vm.q.brandId = brandName;
		vm.q.source=1;
		console.log(vm.q.brandId);
		vm.reload();
	}
})
$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/bvideoinfo/queryList',
        datatype: "json",
        colModel: [
			{ label: 'id', name: 'id', index: 'id',align: "center", width: 60, key: true},
			{ label: '视频名称', name: 'articleTitle', index: 'article_title',align: "center", width: 220},
			{ label: '创建时间', name: 'createTime',dataType: "date", sortable: true, index: 'create_time',align: "center", width: 140 },
			{ label: '品牌/分类', name: 'articleTypeName', index: 'articleTypeName',align: "center", width: 80 },
			{ label: '创建者', name: 'userName', index: 'userName',align: "center", width: 50,
				formatter:function(value,options,rowData){
				var source=rowData["articleSource"]
				if(source==1){
					return value;
				}else{
					var userId = rowData["userId"];
					if(value==""){
						return "";
					}else {
						return "<a onclick=vm.openUser("+userId+")>" + value + "</a>";
					}
				}
				}
			},
            { label: '分享', name: 'articleShareCount',dataType: "int", sortable: true, index: 'article_share_count',align: "center", width: 40 },
            { label: '热度', name: 'articleHotScore',dataType: "int", sortable: true, index: 'article_hot_score',align: "center", width: 50
                // ,
                // formatter:function(value,options,rowData){
                // 	return value;
                // }
            },
            { label: '查看', name: 'articleOutReadCount',dataType: "int", sortable: true, index: 'article_out_read_count',align: "center", width: 40 },
            { label: '热门', name: 'articleRecommendStatus',sortable: false, index: 'articleRecommendStatus',align: "center", width: 40 ,
                formatter:function(value,options,rowData){
                    var content="";
                    var id=rowData["id"];
                    if( value===0 || value=="" || value==null){
                        content="<a style='text-align: center'onclick=vm.updateStatus('"+id+"',3)>"+"否"+"</a>"
                    }else if(value==1){
						content="<a style='text-align: center'onclick=vm.updateStatus('"+id+"',4)>"+ "<strong style='color: red'>"+'是'+"</>"+"</a>";
                    }
                    return content;
                }},
            { label: '来源', name: 'articleSource', index: 'article_source',align: "center", width: 40 ,
                formatter:function(value,options,rowData){
                    var thirdSource=rowData["thirdArticleSource"];
                    var source=rowData["articleSource"];
                    var content="";
                    if(source==1&&thirdSource==1){
                        content= "好文";
                    }else if(source==1&&thirdSource==2){
                        content= "V名片"
                    }else if(source==1&&thirdSource!=null&&thirdSource.length>1){
                        content= thirdSource;
                    }else if( value===1 ){
                        content= "平台";
                    }else if(value==2){
                        content= "用户";
                    }else if(value==3){
                        content= '用户'
                    }
                    return content;
                }
            },
            { label: '状态', name: 'articleStatus', index: 'article_status',align: "center", width: 40 ,
                formatter:function(value,options,rowData){
                    var content="";
                    if( value===1 ){
                        content= '正常';
                    }else if(value==0){
                        content= "<p style='color: red'>"+'删除'+"</>"
                    }else if(value==2){
                        content= '隐藏';
                    }
                    return content;
                }
            },
            { label: '操作', name: '', index: '',align: "center", width: 130,
                formatter:function(value,options,rowData){
                    var status=rowData["articleStatus"];
                    var id=rowData["id"];
                    var content="";
                    if( status===1 ){
                        content= "<a style='text-align: center' class='btn btn-primary' onclick=vm.updateStatus('"+id+"',0)>"+"删除"+"</a>";
                        // return "<a title='删除'>"+"<i style='font-size: 20px' class='fa fa-trash-o' onclick=vm.updateStatus('"+id+"',0)>"+"</i>"+"</a>"+'&nbsp;&nbsp;'+
                        //     "<a title='热门'>"+"<i style='font-size: 20px' class='fa fa-fire' onclick=vm.updateStatus('"+id+"',3)>"+"</i>"+"</a>";
                    }else if(status==0||status==2){
                        content= "<a style='text-align: center' class='btn btn-primary' onclick=vm.updateStatus('"+id+"',1)>"+"恢复"+"</a>";
                    }
                    content=content+ "<a style='text-align: center' class='btn btn-primary' onclick=vm.editInfo('"+id+"',1)>"+"修改"+"</a>";
					content=content+ "<a style='text-align: center' class='btn btn-primary' onclick=loadArticleDetail('"+id+"',2)>"+"详情"+"</a>";
                    return content;
                }
            }
        ],
		viewrecords: true,
        height: "100%",
        rowNum: 12,
		rowList : [12,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        postData:{'articleTitle':vm.q.articleTitle,'articleTypeName': vm.q.articleTypeName,"brandId":vm.q.brandId,"source":vm.q.source},
        gridComplete:function(){
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
});
setTimeout(function (){
	$.ajax({
		type: "POST",
		async:false,
		url: baseURL + 'sys/bbrandinfo/queryAll',
		contentType: "application/json",
		success: function(r){
			if(r.code==0){
				//vm.bbrandinfo=r.brandInfo;
				for(var i=0;i<r.brandInfo.length;i++){
					$("#brandName").append(
						"<option value=" + r.brandInfo[i].brandName +">"+"</option>");
				}
			}
		}
	});
}, 2000);
function timesFun (timesData) {
	//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
	var dateBegin = new Date(timesData.replace(/-/g, "/"));//将-转化为/，使用new Date
	var dateEnd = new Date();//获取当前时间
	var dateDiff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数
	var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
	var leave1 = dateDiff % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000))//计算出小时数
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000)    //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000))//计算相差分钟数
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);
	var timesString = '';

	if (dayDiff == 0 && hours != 0) {
		timesString = hours;
	}
	return {
		timesString: timesString
	}
}
var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
            articleTypeName:"",
            articleTitle:"",
            brandId:"",
            desc:"",
            articleSource:"",
            source:""
		},
		showList: true,
		title: null,
		bVideoInfo: {},
		bbrandinfo:{},
        articleTypeName:null,
        articleTitle:null,
        barticletypeinfo:{},
		pp:'pp',
		lx:'lx',
		page:0,
		bArticleStand:{},
		hebing:true
	},
	methods: {
		addPushArticle: function () {
			let startTime = document.getElementById("startTime1");
			let timeStart = new Date(startTime.value).getTime();

			let endTime = document.getElementById("endTime1");
			let timeEnd = new Date(endTime.value).getTime();

			console.info(startTime);
			console.info(endTime);

			console.info(timeStart);
			console.info(timeEnd);

			if (!(timeStart > 0) || !(timeEnd > 0)) {
				alert('请选择正确的推送时间');
				return;
			}

			if (timeStart > timeEnd ) {
				alert('开始时间不能大于结束时间');
				return;
			}

			let bArticleInfo = {
				id: vm.bVideoInfo.id,
				articleTypeId: vm.bVideoInfo.articleTypeId,
				resourceType: vm.bVideoInfo.resourceType,
				timeStart: timeStart,
				timeEnd: timeEnd,
			};
			$.ajax({
				type: "POST",
				url: baseURL + "sys/barticlestand/savePush",
				contentType: "application/json",
				data: JSON.stringify(bArticleInfo),
				success: function (r) {
					if (r.code == 0) {
						alert('操作成功', function (index) {
							layer.closeAll();
							$("#jqGrid").trigger("reloadGrid");
						});
					} else {
						alert(r.msg);
					}
				}
			});
		},
		openPushArticle: function () {
			let ids = vm.bVideoInfo.id;
			if (ids == null) {
				return;
			}
			$("#startTime1").val("");
			$("#endTime1").val("");
			layer.open({
				type: 1,
				title: '添加到推送文章',
				maxmin: true,
				success: function (layero) {
					layero.find('.layui-layer-btn').css('text-align', 'center')
				},
				shadeClose: true, //点击遮罩关闭层
				area: ['400px', '220px'],
				content: $("#hebing").html()
			});
			//
			// //希望每次打开都要默认为今天日期+00:00
			// //默认时间
			// var myDate = new Date(), Y = myDate.getFullYear(), M = myDate.getMonth() + 1, D = myDate.getDate();
			// //处理月是一位的情况
			// if((M + '').length == 1){
			// 	M = '0' + (M + '');
			// }
			// //处理日是一位的情况
			// if((D + '').length == 1){
			// 	D = '0' + (D + '')
			// }
			// var curDay = Y + '-' + M + '-' + D;
			// console.log(curDay)
			// $('#datetime').val(curDay + 'T00:00')
		},
		getValueStart: function (e) {
			$("#startTime1").val(e.value);
		},
		getValueEnd: function (e) {
			$("#endTime1").val(e.value);
		},
		query: function () {
			vm.q.brandId="";
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.bVideoInfo = {};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id)
		},
		status:function(event){
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.bVideoInfo={};
			vm.bVideoInfo.articleStatus=event;
			vm.bVideoInfo.id=id;
			var url = "sys/bvideoinfo/update";
			confirm('确定隐藏吗状态？', function() {
				$.ajax({
					type: "POST",
					url: baseURL + url,
					contentType: "application/json",
					data: JSON.stringify(vm.bVideoInfo),
					success: function (r) {
						if (r.code === 0) {
							alert('操作成功', function (index) {
								$("#jqGrid").trigger("reloadGrid");
								//window.location.href="../../../templates/modules/sys/buserinfo.html";
								// window.location.href=baseURL+"sys/permissions/index/"+userId;
							});
						} else {
							alert(r.msg);
						}
					}
				});
			});

		},
		updateStatus: function (ids,event) {
			vm.bVideoInfo={};
			confirm('确定修改状态？', function(){
				if(event==3 || event=="3"){
					vm.bVideoInfo.articleRecommendStatus=1;
				} else if(event==4 || event=="4"){
					vm.bVideoInfo.articleRecommendStatus=0;
				}else{
					vm.bVideoInfo.articleStatus=event;
				}
				vm.bVideoInfo.id=ids;
				console.log(vm.bVideoInfo)
				var url = "sys/bvideoinfo/update";
				$.ajax({
					type: "POST",
					url: baseURL + url,
					contentType: "application/json",
					data: JSON.stringify(vm.bVideoInfo),
					success: function(r){
						if(r.code === 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
								//window.location.href="../../../templates/modules/sys/buserinfo.html";
								// window.location.href=baseURL+"sys/permissions/index/"+userId;
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
        editInfo: function (ids,event) {
            //window.location.href="../sys/bvideo_edit.html?id="+ids;
			window.open("../sys/bvideo_edit.html?id="+ids);
        },
		addInfo: function (ids,event) {
			//window.location.href="../sys/bvideo_edit.html?id="+ids;
			window.open("../sys/bvideo_add.html?id="+ids);
		},
		gotoAddDouDou: function (ids,event) {
			window.open("../sys/bvideo_add_doudou.html?id="+ids);
		},
        updateInfo: function (event) {
            var url = vm.bVideoInfo.id == null ? "sys/bvideoinfo/save" : "sys/bvideoinfo/updateInfo";

            //var url =  "sys/barticleinfo/updateInfo";

            //vm.bArticleInfo.articleBrandId=$('#articleBrandId option:selected').val();
            vm.bVideoInfo.brandName=$('#brandName').val();
            vm.bVideoInfo.articleTypeName=$('#articleTypeName').val();
			//vm.bVideoInfo.videoHeight =$('#videoHeight').val();
            console.log( "vm.bVideoInfo.brandName:"+vm.bVideoInfo.brandName);

            //vm.bVideoInfo.articleContent =window.current_editor.getContent();
            //console.log("bArticleInfo Save:"+vm.bArticleInfo);
            if(vm.bVideoInfo.brandName=="" && vm.bVideoInfo.articleTypeName==""){
                alert("请选择品牌或者分类,注意只能选择其中一项");
                return;
            }

            if(vm.bVideoInfo.brandName!="" && vm.bVideoInfo.articleTypeName!=""){
                alert("品牌或者分类,只能选择其中一项");
                return;
            }
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json;charset=UTF-8",
                data:JSON.stringify(vm.bVideoInfo),
                dataType: "JSON",
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
							window.close();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
		saveInfo: function (event) {
			var url = vm.bVideoInfo.id == null ? "sys/bvideoinfo/save" : "sys/bvideoinfo/save";

			var strArticleTypeNames="";
			if($(".pArticleTypeName").length>0){
				$(".pArticleTypeName").each(function(){

					strArticleTypeNames=strArticleTypeNames+","+$(this).attr("value");
				});
				strArticleTypeNames=strArticleTypeNames.substring(1);
			}
			vm.bVideoInfo.brandName=strArticleTypeNames;

			vm.bVideoInfo.articleTypeName=$('#articleTypeName').val();

			if(vm.bVideoInfo.brandName=="" && vm.bVideoInfo.articleTypeName==""){
				alert("请选择品牌或者分类,注意只能选择其中一项");
				return;
			}

			if(vm.bVideoInfo.brandName!="" && vm.bVideoInfo.articleTypeName!=""){
				alert("品牌或者分类,只能选择其中一项");
				return;
			}

			if(vm.bVideoInfo.videoHeight == "" || !(/(^[1-9]\d*$)/.test(vm.bVideoInfo.videoHeight))){
				alert("视频高度填写不正确！");
				return;
			}

			vm.bVideoInfo.articleVersionNum=$("input[name='articleVersionNum']:checked").val();
			vm.bVideoInfo.hotType=$("input[name='hotType']:checked").val();
			$.ajax({
				type: "POST",
				url: baseURL + url,
				contentType: "application/json;charset=UTF-8",
				data:JSON.stringify(vm.bVideoInfo),
				dataType: "JSON",
				success: function(r){
					if(r.code === 0){
						alert('操作成功', function(index){
							window.close();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		createrInfo: function (event) {
			var url = "sys/bvideoinfo/createrInfo";

			var douDouShareLink = $('#douDouShareLink').val();

			$('#douDouShareLink').next().attr("disabled", true);

			$.ajax({
				type: "POST",
				url: baseURL + url,
				contentType: "application/json;charset=UTF-8",
				data:JSON.stringify(douDouShareLink),
				dataType: "JSON",
				success: function(r){
					if(r.code === 0){
						console.log(r.articleInfoDto);
						alert('操作成功', function(index){
							vm.bVideoInfo = r.articleInfoDto;

							$("#articleImgUrl").attr("src", vm.bVideoInfo.articleImgUrl);

							$("#videoUrl").attr("src", vm.bVideoInfo.videoUrl);

							if(vm.bVideoInfo.articleImgUrl != null || vm.bVideoInfo.articleImgUrl != "" || vm.bVideoInfo.videoHeight == null ){
								let img = new Image();
								img.src = vm.bVideoInfo.articleImgUrl;
								vm.bVideoInfo.videoHeight = Math.ceil(img.height / img.width * 750);

								console.log(vm.bVideoInfo.videoHeight);
							}
							vm.bVideoInfo.articleVersionNum=2;
							vm.bVideoInfo.hotType=0;
							// window.close();
						});
					}else{
						alert(r.msg);
					}
					$('#douDouShareLink').next().attr("disabled", false);
					$("input[name='articleVersionNum'][value='2']").prop("checked", "checked");
					$("input[name='hotType'][value='0']").prop("checked", "checked");
				}
			});
		},

		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}

			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/bvideoinfo/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$("#type").empty();
			$.get(baseURL + "sys/bvideoinfo/info/"+id, function(r){
                vm.bVideoInfo = r.bVideoInfo;
                if(r.type==1) {
					$.get(baseURL + "sys/barticletypeinfo/list/", function (r) {
						vm.barticletypeinfo = r.page.list;
						$("#type").append(
							"<option value=" + vm.lx + ">" + '请选择分类' + "</option>");
						for (i = 0; i < vm.barticletypeinfo.length; i++) {
							$("#type").append(
								"<option value=" + vm.barticletypeinfo[i].id + ">" + vm.barticletypeinfo[i].articleTypeName + "</option>");
							$("#type").find("option[value='" + vm.bVideoInfo.articleTypeId + "']").attr("selected", true);
						}
					});
				}else{
					$.get(baseURL + "sys/bbrandinfo/list/", function (r) {
						vm.barticletypeinfo = r.page.list;
						$("#type").append(
							"<option value=" + vm.pp + ">" + '请选择品牌' + "</option>");
						for (i = 0; i < vm.barticletypeinfo.length; i++) {
							$("#type").append(
								"<option value=" + vm.barticletypeinfo[i].id + ">" + vm.barticletypeinfo[i].brandName + "</option>");
							$("#type").find("option[value='" + vm.bVideoInfo.articleBrandId + "']").attr("selected", true);
						}
					});
				}
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = 1;
			console.log(page);
			vm.q.articleTypeName=$("#brandNames").val();
			vm.q.desc=$('#desc option:selected').val();
			vm.q.videoRecommendStatus="";
			var videoSource=$("#videoSource").val();
			var source="";
			if(videoSource=="管理员"){
				source=1;
			}else if(videoSource=="用户"){
				source=2;
			}else if(videoSource=="V名片"){
				source=4;
			}else if(videoSource=="公众号"){
				source=5;
			}
			$("#jqGrid").jqGrid('setGridParam',{
				url: baseURL + 'sys/bvideoinfo/queryList',
				postData:{'desc':vm.q.desc,'articleTitle':vm.q.articleTitle,'articleTypeName': vm.q.articleTypeName,"brandId":vm.q.brandId,"articleRecommendStatus":vm.q.articleRecommendStatus,"source":source},
                page:page
            }).trigger("reloadGrid");
		},
		hot:function () {
			vm.showList = true;
			var page = 1;
			vm.q.articleTypeName=$("#brandNames").val();
			vm.q.videoRecommendStatus=1;
			console.log(vm.q.videoTypeName)
			$("#jqGrid").jqGrid('setGridParam',{
				url: baseURL + 'sys/bvideoinfo/queryList',
				postData:{'articleTitle':vm.q.articleTitle,'articleTypeName': vm.q.articleTypeName,"brandId":vm.q.brandId,"articleRecommendStatus":vm.q.articleRecommendStatus},
				page:page
			}).trigger("reloadGrid");
		},
		openArticle:function (e) {
			layer.open({
				type: 2,
				title: '文章信息',
				maxmin: true,
				shadeClose: true, //点击遮罩关闭层
				area : ['420px' , '650px'],
				content: "test.html?id="+e
			});
		},
		openUser:function (e) {
			layer.open({
				type: 2,
				title: '用户信息',
				maxmin: true,
				shadeClose: true, //点击遮罩关闭层
				area : ['600px' , '650px'],
				content: "buserinfo.html?id="+e
			});
		},
		putArticle:function () {
			$.get(baseURL + "sys/bvideoinfo/putArticle", function(r){
				if(r.code==0){
					alert("入库成功");
				}
			});
		}
	},
    created:function () {

    }
});
